<?php
/**
 * Created by PhpStorm.
 * User: zng
 * Date: 2020/1/3
 * Time: 18:19
 */
namespace app\http\workman;

use think\worker\Server;
use Workerman\Connection\TcpConnection;
use app\admin\service\customer\Worker as WorkerService;

Class Worker extends Server {

    /**
     * 服务器链接
     * @var string
     */
    protected $host = '127.0.0.1';

    /**
     * 监听端口
     * @var int
     */
    protected $port = 8008;

    public function __construct()
    {
        parent::__construct();
        $this->option = [
            'count'		=> 4,
            'pidFile'   => env('runtime_path') . 'worker.pid',
            'name'		=> 'think'
        ];
    }

    /**
     * 消息处理
     * @param TcpConnection $connection
     * @param string $data 用户发来的消息
     * @return void
     */
    public function onMessage($connection, $data):void
    {
        if ( is_json($data) ) {
            $connection->send(failed('MESSAGE IS NULL'));
            return;
        }
        $json = json_decode($data, true);
        $method_name = 'worker_'.($json['type']??'error');
        if ( ! method_exists(WorkerService::class, $method_name) ) {
            $connection->send(failed('SERVICE ERROR'));
            return;
        }
        $connection->send(call_user_func_array([WorkerService::class, $method_name], $json));
    }

    /**
     * 断开连接
     * @param string $client_id 链接id
     */
    public function onClose($client_id)
    {

    }

}